package com.gdufe.studytogether.service.user.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.studytogether.domain.pojo.User;
import com.gdufe.studytogether.mapper.UserMapper;
import com.gdufe.studytogether.service.user.UserService;
import com.gdufe.studytogether.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User selectByUsername(String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username",username);
        User user = this.getOne(qw);
        return user;
    }

    @Override
    public List<User> getTeachers() throws Exception {
        Integer uid = UserThreadLocal.get();
        User user = userMapper.selectById(uid);
        if (user.getRoleId()!=3&&user.getRoleId()!=1){
            return null;
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("roleid",3);
        List<User> teachers = userMapper.selectList(userQueryWrapper);
        return teachers;
    }

    @Override
    public void edit(User user) throws Exception {
        Integer uid = UserThreadLocal.get();//当前登录用户id
        User userInfo = userMapper.selectById(uid);
        Integer roleId=null;
        if (userInfo.getRoleId()==1){
            //为管理员，可以修改其他用户的
            userInfo = userMapper.selectById(user.getId());
            roleId = user.getRoleId();
        }
        String img = user.getImg();
        String grade = user.getGrade();
        String major = user.getMajor();
        String intro = user.getIntro();
        String phone = user.getPhone();
        String email = user.getEmail();
        if (img!=null){
            userInfo.setImg(img);
        }
        if (grade!=null){
            userInfo.setGrade(grade);
        }
        if (major!=null){
            userInfo.setMajor(major);
        }
        if (intro!=null){
            userInfo.setIntro(intro);
        }
        if (roleId!=null){
            userInfo.setRoleId(roleId);
        }
        if (phone!=null){
            userInfo.setPhone(phone);
        }
        if (email!=null){
            userInfo.setEmail(email);
        }
        userMapper.updateById(userInfo);
    }

    @Override
    public User show(Integer uid) throws Exception {

        User userInfo = userMapper.selectById(uid);
        if (userInfo==null){
            throw new Exception("用户不存在");
        }
        userInfo.setPassword(null);
        return userInfo;
    }


}
